using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 角色关系分析器 - 分析和构建角色关系网络
    /// </summary>
    public class CharacterRelationshipAnalyzer
    {
        private readonly ILogger<CharacterRelationshipAnalyzer> _logger;
        private readonly IAIService _aiService;

        public CharacterRelationshipAnalyzer(
            ILogger<CharacterRelationshipAnalyzer> logger,
            IAIService aiService)
        {
            _logger = logger;
            _aiService = aiService;
        }

        /// <summary>
        /// 生成基础关系网络
        /// </summary>
        public async Task<List<CharacterRelationship>> GenerateBasicRelationshipsAsync(List<PlannedCharacter> characters)
        {
            try
            {
                _logger.LogInformation($"为 {characters.Count} 个角色生成基础关系网络");

                var relationships = new List<CharacterRelationship>();

                // 为主要角色建立关系
                var mainCharacters = characters.Where(c => c.Importance <= CharacterImportance.Secondary).ToList();
                
                for (int i = 0; i < mainCharacters.Count; i++)
                {
                    for (int j = i + 1; j < mainCharacters.Count; j++)
                    {
                        var relationship = await GenerateRelationshipBetweenCharactersAsync(
                            mainCharacters[i], mainCharacters[j]);
                        
                        if (relationship != null)
                        {
                            relationships.Add(relationship);
                        }
                    }
                }

                _logger.LogInformation($"生成了 {relationships.Count} 个角色关系");
                return relationships;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成基础关系网络失败");
                return new List<CharacterRelationship>();
            }
        }

        /// <summary>
        /// 分析和规划关系网络
        /// </summary>
        public async Task<List<CharacterRelationship>> AnalyzeAndPlanRelationshipsAsync(
            List<Character> existingCharacters, 
            List<string> targetCharacters)
        {
            try
            {
                _logger.LogInformation("分析和规划角色关系网络");

                var relationships = new List<CharacterRelationship>();

                // 分析现有关系
                var existingRelationships = await AnalyzeExistingRelationshipsAsync(existingCharacters);
                relationships.AddRange(existingRelationships);

                // 为目标角色规划新关系
                foreach (var targetCharacterName in targetCharacters)
                {
                    var targetCharacter = existingCharacters.FirstOrDefault(c => c.Name == targetCharacterName);
                    if (targetCharacter != null)
                    {
                        var newRelationships = await PlanNewRelationshipsForCharacterAsync(
                            targetCharacter, existingCharacters);
                        relationships.AddRange(newRelationships);
                    }
                }

                return relationships;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析和规划关系网络失败");
                return new List<CharacterRelationship>();
            }
        }

        /// <summary>
        /// 在两个角色之间生成关系
        /// </summary>
        private async Task<CharacterRelationship?> GenerateRelationshipBetweenCharactersAsync(
            PlannedCharacter character1, 
            PlannedCharacter character2)
        {
            try
            {
                var prompt = $@"请分析以下两个角色之间可能的关系：

角色1：
- 名称：{character1.Name}
- 类型：{character1.Type}
- 描述：{character1.Description}

角色2：
- 名称：{character2.Name}
- 类型：{character2.Type}
- 描述：{character2.Description}

请确定他们之间的关系类型（朋友/敌人/家人/师生/盟友/对手/恋人等）和关系强度（1-10），
如果没有明显关系，请返回'无关系'。

格式：关系类型|关系强度|关系描述";

                var response = await _aiService.GenerateTextAsync(prompt, 500, 0.6f);
                
                if (response.Contains("无关系"))
                {
                    return null;
                }

                return ParseRelationshipResponse(response, character1.Id, character2.Id);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"生成角色关系失败: {character1.Name} - {character2.Name}");
                return null;
            }
        }

        /// <summary>
        /// 解析关系响应
        /// </summary>
        private CharacterRelationship? ParseRelationshipResponse(string response, string fromCharacterId, string toCharacterId)
        {
            try
            {
                var parts = response.Split('|');
                if (parts.Length >= 3)
                {
                    var relationshipType = ParseRelationshipType(parts[0].Trim());
                    var strength = int.TryParse(parts[1].Trim(), out var s) ? s : 5;
                    var description = parts[2].Trim();

                    return new CharacterRelationship
                    {
                        FromCharacterId = fromCharacterId,
                        ToCharacterId = toCharacterId,
                        Type = relationshipType,
                        Strength = Math.Max(1, Math.Min(10, strength)),
                        Description = description
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析关系响应失败");
            }

            return null;
        }

        /// <summary>
        /// 解析关系类型
        /// </summary>
        private RelationshipType ParseRelationshipType(string typeString)
        {
            return typeString.ToLower() switch
            {
                "家人" or "family" => RelationshipType.Family,
                "朋友" or "friend" => RelationshipType.Friend,
                "敌人" or "enemy" => RelationshipType.Enemy,
                "师父" or "老师" or "mentor" => RelationshipType.Mentor,
                "学生" or "弟子" or "student" => RelationshipType.Student,
                "盟友" or "ally" => RelationshipType.Ally,
                "对手" or "rival" => RelationshipType.Rival,
                "恋人" or "romantic" => RelationshipType.Romantic,
                _ => RelationshipType.Friend
            };
        }

        /// <summary>
        /// 分析现有关系
        /// </summary>
        private async Task<List<CharacterRelationship>> AnalyzeExistingRelationshipsAsync(List<Character> characters)
        {
            var relationships = new List<CharacterRelationship>();

            try
            {
                // 这里应该从数据库或文件中读取现有关系
                // 暂时返回空列表
                _logger.LogInformation("分析现有角色关系");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析现有关系失败");
            }

            return relationships;
        }

        /// <summary>
        /// 为角色规划新关系
        /// </summary>
        private async Task<List<CharacterRelationship>> PlanNewRelationshipsForCharacterAsync(
            Character targetCharacter, 
            List<Character> allCharacters)
        {
            var relationships = new List<CharacterRelationship>();

            try
            {
                var prompt = $@"请为以下角色规划新的关系网络：

目标角色：
- 名称：{targetCharacter.Name}
- 描述：{targetCharacter.Description}

其他角色：
{string.Join("\n", allCharacters.Where(c => c.Id != targetCharacter.Id).Select(c => $"- {c.Name}: {c.Description}"))}

请建议目标角色与其他角色之间应该建立什么样的关系，包括关系类型和原因。
格式：角色名|关系类型|关系强度|关系描述";

                var response = await _aiService.GenerateTextAsync(prompt, 1500, 0.7f);
                relationships = ParseMultipleRelationshipsResponse(response, targetCharacter.Id.ToString(), allCharacters);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"为角色规划新关系失败: {targetCharacter.Name}");
            }

            return relationships;
        }

        /// <summary>
        /// 解析多个关系响应
        /// </summary>
        private List<CharacterRelationship> ParseMultipleRelationshipsResponse(
            string response, 
            string fromCharacterId, 
            List<Character> allCharacters)
        {
            var relationships = new List<CharacterRelationship>();

            try
            {
                var lines = response.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                
                foreach (var line in lines)
                {
                    var parts = line.Split('|');
                    if (parts.Length >= 4)
                    {
                        var characterName = parts[0].Trim().TrimStart('-', ' ');
                        var targetCharacter = allCharacters.FirstOrDefault(c => 
                            c.Name.Equals(characterName, StringComparison.OrdinalIgnoreCase));
                        
                        if (targetCharacter != null)
                        {
                            var relationshipType = ParseRelationshipType(parts[1].Trim());
                            var strength = int.TryParse(parts[2].Trim(), out var s) ? s : 5;
                            var description = parts[3].Trim();

                            relationships.Add(new CharacterRelationship
                            {
                                FromCharacterId = fromCharacterId,
                                ToCharacterId = targetCharacter.Id.ToString(),
                                Type = relationshipType,
                                Strength = Math.Max(1, Math.Min(10, strength)),
                                Description = description
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析多个关系响应失败");
            }

            return relationships;
        }

        /// <summary>
        /// 验证关系网络的合理性
        /// </summary>
        public async Task<RelationshipValidationResult> ValidateRelationshipNetworkAsync(
            List<CharacterRelationship> relationships, 
            List<Character> characters)
        {
            try
            {
                _logger.LogInformation("验证关系网络合理性");

                var result = new RelationshipValidationResult
                {
                    IsValid = true,
                    ValidationTime = DateTime.Now
                };

                // 检查关系的一致性
                var inconsistencies = FindRelationshipInconsistencies(relationships);
                result.Issues.AddRange(inconsistencies);

                // 检查孤立角色
                var isolatedCharacters = FindIsolatedCharacters(relationships, characters);
                if (isolatedCharacters.Any())
                {
                    result.Issues.Add($"发现孤立角色: {string.Join(", ", isolatedCharacters)}");
                }

                // 检查关系强度分布
                var strengthDistribution = AnalyzeRelationshipStrengthDistribution(relationships);
                if (strengthDistribution.AverageStrength < 3)
                {
                    result.Suggestions.Add("关系网络整体强度较低，建议加强角色间的联系");
                }

                result.IsValid = !result.Issues.Any();
                result.Score = CalculateNetworkScore(relationships, characters);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证关系网络失败");
                return new RelationshipValidationResult { IsValid = false };
            }
        }

        /// <summary>
        /// 查找关系不一致性
        /// </summary>
        private List<string> FindRelationshipInconsistencies(List<CharacterRelationship> relationships)
        {
            var issues = new List<string>();

            // 检查双向关系的一致性
            var relationshipPairs = relationships.GroupBy(r => new { 
                Char1 = string.Compare(r.FromCharacterId, r.ToCharacterId) < 0 ? r.FromCharacterId : r.ToCharacterId,
                Char2 = string.Compare(r.FromCharacterId, r.ToCharacterId) < 0 ? r.ToCharacterId : r.FromCharacterId
            });

            foreach (var pair in relationshipPairs)
            {
                var relations = pair.ToList();
                if (relations.Count > 1)
                {
                    // 检查关系类型是否冲突
                    var types = relations.Select(r => r.Type).Distinct().ToList();
                    if (types.Count > 1 && HasConflictingTypes(types))
                    {
                        issues.Add($"角色 {pair.Key.Char1} 和 {pair.Key.Char2} 之间存在冲突的关系类型");
                    }
                }
            }

            return issues;
        }

        /// <summary>
        /// 检查是否有冲突的关系类型
        /// </summary>
        private bool HasConflictingTypes(List<RelationshipType> types)
        {
            var conflictPairs = new[]
            {
                (RelationshipType.Friend, RelationshipType.Enemy),
                (RelationshipType.Ally, RelationshipType.Enemy),
                (RelationshipType.Family, RelationshipType.Enemy)
            };

            return conflictPairs.Any(pair => types.Contains(pair.Item1) && types.Contains(pair.Item2));
        }

        /// <summary>
        /// 查找孤立角色
        /// </summary>
        private List<string> FindIsolatedCharacters(List<CharacterRelationship> relationships, List<Character> characters)
        {
            var connectedCharacters = relationships
                .SelectMany(r => new[] { r.FromCharacterId, r.ToCharacterId })
                .Distinct()
                .ToHashSet();

            return characters
                .Where(c => !connectedCharacters.Contains(c.Id.ToString()))
                .Select(c => c.Name)
                .ToList();
        }

        /// <summary>
        /// 分析关系强度分布
        /// </summary>
        private RelationshipStrengthDistribution AnalyzeRelationshipStrengthDistribution(List<CharacterRelationship> relationships)
        {
            if (!relationships.Any())
            {
                return new RelationshipStrengthDistribution();
            }

            return new RelationshipStrengthDistribution
            {
                AverageStrength = relationships.Average(r => r.Strength),
                MinStrength = relationships.Min(r => r.Strength),
                MaxStrength = relationships.Max(r => r.Strength),
                TotalRelationships = relationships.Count
            };
        }

        /// <summary>
        /// 计算网络评分
        /// </summary>
        private double CalculateNetworkScore(List<CharacterRelationship> relationships, List<Character> characters)
        {
            if (!characters.Any()) return 0;

            var connectivityScore = (double)relationships.Count / (characters.Count * (characters.Count - 1) / 2);
            var strengthScore = relationships.Any() ? relationships.Average(r => r.Strength) / 10.0 : 0;
            var diversityScore = relationships.GroupBy(r => r.Type).Count() / Enum.GetValues<RelationshipType>().Length;

            return (connectivityScore + strengthScore + diversityScore) / 3 * 100;
        }
    }

    /// <summary>
    /// 关系验证结果
    /// </summary>
    public class RelationshipValidationResult
    {
        public bool IsValid { get; set; }
        public double Score { get; set; }
        public List<string> Issues { get; set; } = new();
        public List<string> Suggestions { get; set; } = new();
        public DateTime ValidationTime { get; set; }
    }

    /// <summary>
    /// 关系强度分布
    /// </summary>
    public class RelationshipStrengthDistribution
    {
        public double AverageStrength { get; set; }
        public int MinStrength { get; set; }
        public int MaxStrength { get; set; }
        public int TotalRelationships { get; set; }
    }
}
